
package com.vae.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.vae.search.mapper.SkuSearchMapper;
import com.vae.search.model.SkuEs;
import com.vae.search.service.SkuSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * es 中sku 服务实现类
 */
@Service
public class SkuSearchServiceImpl implements SkuSearchService {
    @Autowired
    private SkuSearchMapper skuSearchMapper;

    /***
     * 添加单个商品到es
     * @param skuEs
     */
    @Override
    public void add(SkuEs skuEs) {
       //属性转换
        String skuAttribute = skuEs.getSkuAttribute();
        if(!StringUtils.isEmpty(skuAttribute)){
            skuEs.setAttrMap(JSON.parseObject(skuAttribute, Map.class));
        }
        skuSearchMapper.save(skuEs);
    }

    /***
     * 根据ID删除
     * @param id
     */
    @Override
    public void del(String id) {
        skuSearchMapper.deleteById(id);
    }

    /**
     * 根据条件搜索
     * @param searchMap
     * @return
     */
    @Override
    public Map<String, Object> search(Map<String, Object> searchMap) {
        //1 构建查询条件
        NativeSearchQuery nativeSearchQuery = this.generateQuery(searchMap);
        //2 执行查询
        Page<SkuEs> skuEsPage = skuSearchMapper.search(nativeSearchQuery);
        //3 封装返回结果
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("list",skuEsPage.getContent());
        resultMap.put("totalElements",skuEsPage.getTotalElements());
        return resultMap;
    }

    //构建es的查询条件
    public NativeSearchQuery generateQuery(Map<String, Object> searchMap){
        //QueryBuilder构建
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //条件判断
        if(searchMap!=null && searchMap.size()>0){
            //关键词查询
            String keyword =(String)searchMap.get("keyword");
            if(!StringUtils.isEmpty(keyword)){
                //先通过name进行查询
                queryBuilder.withQuery(QueryBuilders.termQuery("name",keyword.toString()));
            }
        }
        return queryBuilder.build();
    }

}